import React,{Component} from 'react'
import './index.less'
import { Menu } from 'antd'
import MenuConfig from '../../config/menuConfig'
import {NavLink} from 'react-router-dom'
import { connect } from 'react-redux'
import { switchMenu } from './../../redux/action'

const SubMenu = Menu.SubMenu;
class NavLeft extends Component {
    state = {
        currentKey: ''
    }
    componentWillMount() {
        const menuTreeNode = this.renderMenu(MenuConfig)
        let currentKey = window.location.hash.replace(/#|\?.*$/g,'')
        this.setState({
            currentKey,
            menuTreeNode
        })
    }
    renderMenu = (data) => {
        return data.map(item => {
            if(item.children) {
                return (
                    <SubMenu key={item.key} title={item.title}>
                        {this.renderMenu(item.children)}
                    </SubMenu>
                )
            }
            return (
                <Menu.Item key={item.key} title={item.title}>
                    <NavLink to={item.key}>{item.title}</NavLink>
                </Menu.Item>
            )
        })
    }
    handleClick = ({ item, key }) => {
        //如果就是原来的,不执行下面
        if (key == this.state.currentKey) {
            return false;
        }
        // 事件派发，自动调用reducer，通过reducer保存到store对象中
        this.props.switchMenu(item.props.title)

        this.setState({
            currentKey: key
        })
    };
    render(){
        return (
            <div>
                <div className="logo">
                    <img src="/assets/logo-ant.svg" alt=""></img>
                    <h1>Imooc MS</h1>
                </div>
                
                <Menu 
                    theme="dark"
                    selectedKeys = {this.state.currentKey}
                    onClick={this.handleClick}
                    mode="vertical">
                    {this.state.menuTreeNode}
                </Menu>
            </div>
        )
    }
}
//获取值
const mapStateToProps = (state) => {
    return {
        menuName:state.menuName
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        switchMenu(menuName) {
            dispatch(switchMenu(menuName))
        }
    }
  }

export default connect(mapStateToProps,mapDispatchToProps)(NavLeft)